package jjn.round1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2023-06-09 23:17
 */
public class LeetCode90_SubsetsWithDup {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        boolean[] visited = new boolean[nums.length];
        dfs(nums, result, new ArrayList<>(), 0, visited);
        return result;
    }
    
    private void dfs(int[] nums, List<List<Integer>> set, List<Integer> current, int startIndex, boolean[] visited) {
        set.add(new ArrayList<>(current));
        for (int i = startIndex; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
                continue;
            }
            current.add(nums[i]);
            visited[i] = true;
            dfs(nums, set, current, i + 1, visited);
            current.remove(current.size() - 1);
            visited[i] = false;
        }
    }
}
